#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    QStringList serialNamePort;

    ui->setupUi(this);
    this->setWindowTitle("serial_led from Qt Creator  by 帅哥强");

    /*创建一个串口对象*/
    serialPort = new QSerialPort(this);

    /*搜索所有可用的串口*/
    foreach(const QSerialPortInfo &inf0, QSerialPortInfo::availablePorts()) {
        serialNamePort<<inf0.portName();
    }

    ui->serialBox->addItems(serialNamePort);

    //按键使能
    ui->closeButton->setEnabled(false);
    ui->onButton->setEnabled(false);
    ui->offButton->setEnabled(false);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_openButton_clicked()
{
    //串口设置
    serialPort->setPortName(ui->serialBox->currentText());
    serialPort->setBaudRate(ui->baudrateBox->currentText().toInt());
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setParity(QSerialPort::NoParity);

    //打开串口提示框
    if (true == serialPort->open(QIODevice::ReadWrite))
    {
        QMessageBox::information(this, "提示", "串口打开成功");
    }
    else
    {
        QMessageBox::critical(this, "提示", "串口打开失败");
    }
    //按键使能
    ui->openButton->setEnabled(false);
    ui->closeButton->setEnabled(true);
    ui->onButton->setEnabled(true);
    ui->offButton->setEnabled(true);
}

void Widget::on_closeButton_clicked()
{
    //关闭串口
    serialPort->close();
    //按键使能
    ui->closeButton->setEnabled(false);
    ui->onButton->setEnabled(false);
    ui->offButton->setEnabled(false);
    ui->openButton->setEnabled(true);
}

void Widget::on_onButton_clicked()
{
    //串口发送字符串
    serialPort->write("ON\n");
    //打印调试信息
    qDebug("ON\n");
}

void Widget::on_offButton_clicked()
{
    //串口发送字符串
    serialPort->write("OFF\n");
    //打印调试信息
    qDebug("OFF\n");
}
